package fiuba.webapp.action;


import fiuba.model.LabelValue;
import fiuba.model.Menu;
import fiuba.model.MenuItem;
import fiuba.service.MenuExistsException;
import fiuba.service.MenuItemManager;
import fiuba.service.MenuManager;
import fiuba.service.RoleManager;
import fiuba.service.impl.MenuItemManagerImpl;


import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Preparable;

public class MenuAction extends BaseAction {
    private static final long serialVersionUID = 79803203948203498L;
	private MenuManager menuManager;
	private MenuItemManager menuItemManager;
    private List menus;
    private String id;
    private Menu menu;
    private List <LabelValue> itemsAvailable;
    
    
    // Para el tema de ordenes
	private Map<String,String> menuItemsOrdenados = new LinkedHashMap<String,String>();
	private String nuevoOrden = "";
    
    
    public void setMenuItemManager(MenuItemManager menuItemManager) {
        this.menuItemManager = menuItemManager;
    }
    
    public void setMenuManager (MenuManager menuManager){
    	this.menuManager = menuManager;
    }
    
    public void setId(String id) {
        this.id = id;
    }

    public List getItemsAvailable(){
    	
    	return this.itemsAvailable;
    }
    
    public Menu getMenu(){
    	return menu;
    }
    
    public void setMenu(Menu menu){
    	this.menu = menu;
    }

    public String delete() {
        menuManager.removeMenu(menu.getId().toString());
        saveMessage(getText("menu.deleted"));

        return SUCCESS;
    }
    /**
     * Grab the menu from the database based on the "id" passed in.
     * @return success if user found
     * @throws IOException can happen when sending a "forbidden" from response.sendError()
     */
    public String edit() {
        if (id != null) {
            menu = menuManager.getMenu(id);
        } else {
            menu = new Menu();
        }      
        
        itemsAvailable = menuManager.getMenuItemsNotInMenu(menu);
        return SUCCESS;
    }

    /**
     * Save menu
     * @return success if everything worked, otherwise input
     * @throws IOException when setting "access denied" fails on response
     */
    public String save() throws IOException {
    	if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }
        
        boolean isNew = (menu.getId() == null);
        
        String[] menuItems = getRequest().getParameterValues("menuMenuItems");
        menu.getMenuItems().clear(); 
        menu.setOrden("");
        
        for (int i = 0; menuItems != null && i < menuItems.length; i++ ) {
            String menuItemId = menuItems[i];
            menu.addMenuItem(menuItemManager.getMenuItem(menuItemId));
            if (! menu.getOrden().equals("")) menu.setOrden(menu.getOrden() + ",");
            menu.setOrden(menu.getOrden() + menuItemId);
        }
        
        try {
        	menu = menuManager.saveMenu(menu);	
        }catch(MenuExistsException e){
        	return ERROR;
        }
        
        String key = (isNew) ? "menu.added" : "menu.updated";
        saveMessage(getText(key));
        itemsAvailable = menuManager.getMenuItemsNotInMenu(menu);
        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
        
    }
    
    public List getMenus() {
    	return menus;
    }
    public String list() {
        menus = menuManager.getMenus();
        return SUCCESS;
    }

    /* Cambios de orden */
    public String editOrder() {
        if (id != null) {
        	try {
        		menu = menuManager.getMenu(id);
        	} catch (Exception e) {
        		log.debug("No existe menu: " + id);
        		return ERROR;
        	}
        } else {
            return ERROR;
        }
        
        // Armamos la lista de disponibles
    	String[] arrayOrden = menu.getOrden().split(",");
    	for (int i = 0; i < arrayOrden.length;i++) {
    		Long idActual = Long.parseLong(arrayOrden[i]);
    		for (MenuItem item : menu.getMenuItems()){
    			if (item.getId().equals(idActual)){
//    				log.debug(item.getName());
    				menuItemsOrdenados.put(item.getId().toString(), item.getName());
    			}		
    		}	
    	}

        return SUCCESS;
    }
    
    public String saveOrder() {
	    if (cancel != null) {
	    	log.debug("CANCEL");
	        return CANCEL;
	    }
	    if (nuevoOrden == null || nuevoOrden.equals("")) {
	    	this.editOrder();
	    	return ERROR;
	    }
	    try {
	    	Menu m = this.menuManager.getMenu(id);
	    	m.setOrden(this.getNuevoOrden());
	    	m = this.menuManager.saveMenu(m);
	    }
	    catch(Exception e) {
	    	this.editOrder();
	    	return ERROR;
	    }
	    return SUCCESS;
    }

	public Map<String, String> getMenuItemsOrdenados() {
		return menuItemsOrdenados;
	}

	public void setMenuItemsOrdenados(Map<String, String> menuItemsOrdenados) {
		this.menuItemsOrdenados = menuItemsOrdenados;
	}

	public String getNuevoOrden() {
		return nuevoOrden;
	}

	public void setNuevoOrden(String nuevoOrden) {
		this.nuevoOrden = nuevoOrden;
	}

	public String getId() {
		return id;
	}

	public void setMenus(List menus) {
		this.menus = menus;
	}

	public void setItemsAvailable(List<LabelValue> itemsAvailable) {
		this.itemsAvailable = itemsAvailable;
	}
    
    
}
